import { useCallback, useMemo, useState, ReactElement, useContext } from 'react';
import { getSystemType, ISystemGroup } from '../../designer/service';
import { useRequest, useUpdateEffect } from 'ahooks';
import { IConfigItem } from '../web/components/content';
import { ButtonProps } from 'antd';
import EventContext from './EventContext';
import { getMessage } from '@inbiz/react';
import { getPlatform } from '@inbiz/utils';
let Button: React.ForwardRefExoticComponent<ButtonProps & React.RefAttributes<HTMLElement>>;
if (getPlatform() === 'web') {
  Button = require('antd').Button;
}

export type ISystemGroupChildren = (
  list: ISystemGroup[],
  onClick: (groupName: string) => void,
  selectedGroupName: string,
) => ReactElement;

function SystemGroup({
  config,
  showSystem,
  onChange,
  children,
}: IConfigItem & {
  showSystem: boolean;
  onChange?: (key: string) => void;
  children?: ISystemGroupChildren;
}) {
  const { configEventsApi } = useContext(EventContext);
  // 系统分类
  const { data } = useRequest(
    () => {
      if (showSystem) {
        return configEventsApi({
          request: getSystemType,
          params: config.IndexName,
          keys: ['onSystemTypeParams', 'onSystemType', 'onSystemTypeData'],
        });
      } else {
        return Promise.resolve({
          Code: 0,
          Data: [] as ISystemGroup[],
        });
      }
    },
    {
      refreshDeps: [config, showSystem],
    },
  );
  const showList = useMemo(() => {
    if (data?.Data?.length) {
      return [
        {
          groupName: getMessage('SearchResultEngine.whole'),
          groupNum: '',
        },
        ...data.Data,
      ] as ISystemGroup[];
    } else {
      return [];
    }
  }, [data]);

  const [selected, $selected] = useState('');

  useUpdateEffect(() => {
    $selected(selected || '');
  }, [selected]);
  const handleClick = useCallback(
    (groupNum) => {
      $selected((key) => {
        const newKey = key == groupNum ? '' : groupNum;
        onChange?.(newKey);
        return newKey;
      });
    },
    [onChange],
  );
  if (showList?.length) {
    if (children) {
      return children(showList, handleClick, selected);
    }
    return (
      <div className="systemGroup">
        {showList.map((item) => {
          return (
            <Button
              onClick={() => handleClick(item.groupNum)}
              key={item.groupNum}
              shape="round"
              className={item.groupNum === selected ? 'selected' : ''}
            >
              {item.groupName}
            </Button>
          );
        })}
      </div>
    );
  } else {
    return null;
  }
}
export default SystemGroup;
